package models

import (
	"gorm.io/gorm"
)

type Product struct {
	gorm.Model
	Name        string  `gorm:"type:varchar(30);not null;comment:'商品名称'"`
	Price       float64 `gorm:"type:decimal(10,2);not null;comment:'商品价格'"`
	Description string  `gorm:"type:varchar(100);not null;comment:'商品描述'"`
	Stock       int     `gorm:"type:int(100);not null;comment:'商品库存'"`
}

func (u *Product) Update() error {
	return DB.Updates(&u).Error
}

func (u *Product) GetProBy() error {
	return DB.Where("name = ?", u.Name).Limit(1).Find(&u).Error
}

func (u *Product) Del() error {
	return DB.Delete(&u).Error
}

func (u *Product) List(keyword string, page, pageSize int) (list []*Product, err error) {
	err = DB.Where("name like ?", "%"+keyword+"%").Scopes(Paginate(page, pageSize)).Find(&list).Error
	return
}

func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
